import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:upgrade/custom_exception.dart';
import 'package:upgrade/upgrade_manager.dart';
import 'package:upgrade/upgrade_manager_option.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _upgradePlugin = UpgradeManager.instance();

  @override
  void initState() {
    super.initState();
    initPlatformState();
    _initUpgrade();
  }

  _checkUpgrade(BuildContext buildContext) {
    _upgradePlugin
        .optionBuilder(context)
        .doOnCancelUpgrade((isForce) {
          print("取消下载");
          Navigator.pop(context);
          if (isForce) {
            pop().then((value) {
              exit(0);
            });
          }
        })
        .build()
        .checkUpgrade((CustomException e) {
          print(e);
        }, () {});
  }

  Future<void> pop() async {
    await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

  _initUpgrade() {
    var option = UpgradeManagerOption();
    option.downloadHost = "http://192.168.31.45:8080";
    option.host = "http://192.168.31.45:8080";
    option.appKey = "315cca7895a200771c4a18f1a1c52b44";
    option.printLog = true;
    _upgradePlugin.init(option: option);
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _upgradePlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            _checkUpgrade(context);
            /*  showDialog(context: context, builder: (bc){
              return Container(color: Colors.orange,);
            });*/
          },
          child: Text("asdfasf"),
        ),
      ),
    );
  }
}
